package com.yz.jdd.module.cashier.scanpay;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;


import com.qiniu.android.utils.StringUtils;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.IntentHandler;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.cashier.result.PayFailureActivity;
import com.yz.jdd.module.cashier.result.PaySuccessActivity;
import com.yz.jdd.module.cashier.scanpay.exception.ExceptionPresenter;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.network.request.Request_PayStatus;
import com.yz.jdd.network.response.Response_Pay;
import com.yz.jdd.scan.Scanner;
import com.yz.jdd.scan.SoftwareScanner;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by shibin on 2017/2/27.
 */

public class ScanpayPresenter extends ExceptionPresenter implements ScanpayContract.Presenter {
    private ScanpayContract.ScanpayView iScanpayView;
    private ScanpayContract.IScanpayModel scanpayModel;
    private SoftwareScanner softwareScanner;
    private Context context;
    private String orderId = "";//订单号
    //    private List<Coupon> couponList;
    private Subscription periodSubscribtion;
    private Subscription statusSubscribtion;
    private List<Subscription> subscriptionList;//记录订单状态请求集合
    private boolean getStatus;//是否得到状态
    private Subscription paySubscribtion;
    private String clientOrderId = "";
    private Request_Pay args;
    private String dealType;
    private Observable observable;


    public ScanpayPresenter(Context context, ScanpayContract.ScanpayView iScanpayView, Scanner softwareScanner) {
        super(context, iScanpayView);
        this.iScanpayView = iScanpayView;
        scanpayModel = new ScanpayModelImpl(context);
        this.softwareScanner = (SoftwareScanner) softwareScanner;
        this.context = context;
        iScanpayView.setPresenter(this);
        observable = Observable.interval(0, 3, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread());
        subscriptionList = new ArrayList<>();
        getStatus = false;
    }


    /**
     * 支付宝/微信支付
     *
     * @param request_pay 参数
     */
    @Override
    public void toPay(final Request_Pay request_pay) {
        dealType = request_pay.getOrderType();
        if (PayConfig.TYPE_SUBPAY_TOSCAN.equals(request_pay.getSubPayType())) {
            //主扫
            iScanpayView.showPayLoadingNoCancelable("支付中,请稍候...");
        } else {
            //被扫
            iScanpayView.showPayLoadingNoCancelable("加载中,请稍候...");
        }
        //生成 ClientOrderId
        clientOrderId = PayConfig.createClientOrderId(context);
        request_pay.setClientOrderId(clientOrderId);
        String shopId = PreferencesUtils.getString(context, BaseConfigs.PREF_CASH_SHOPID, "");
        if (!StringUtils.isNullOrEmpty(shopId)) {
            request_pay.setShopId(shopId);
        }

        args = request_pay;


        paySubscribtion = scanpayModel.doPay(request_pay, new ApiCallback() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                unsubscribePay();

                final Response_Pay response_pay = (Response_Pay) response_baseModel.getResultObject();
                if (response_pay != null) {
//                    if (PayConfig.TYPE_SUBPAY_TOSCAN.equals(response_pay.getSubPayType())) {
                    if (true) {
                        iScanpayView.dismissPayLoading();
                        if (PayConfig.ORDER_STATUS_SUCCESS.equals(response_pay.getPayStatus())) {

                            //发消息,刷新首页/列表数据
                            RxBus.getInstance().send(Events.EVENT_VOICE_BROADCAT, "scanpay");

                            Intent intent = new Intent(context, PaySuccessActivity.class);
                            Bundle result_bundle = new Bundle();
                            request_pay.setReceiptAmount(response_pay.getReceiptAmount());
                            request_pay.setDiscountAmount(response_pay.getDiscountAmount());
                            request_pay.setTotalAmount(response_pay.getTotalAmount());
                            request_pay.setPayType(response_pay.getPayType());
//                            request_pay.setOrderType(response_pay.getOrderType());
//                            request_pay.setOrderType(dealType);
                            request_pay.setOrderId(response_pay.getOrderId());
//                            request_pay.setGoodsAmount(response_pay.getGoodsAmount());
                            request_pay.setGooodsAmount(response_pay.getGooodsAmount());
                            //营销新增
                            request_pay.setDeductionAmount(response_pay.getDeductionAmount());
                            request_pay.setReceiveAmountFromPayGate(response_pay.getReceiveAmountFromPayGate());

                            result_bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);

                            intent.putExtras(result_bundle);
                            context.startActivity(intent);

//                            //打印
//                            if (!PayConfig.TYPE_ORDER_DISH.equals(response_pay.getOrderType())) {
//                                doPrinter(response_pay, null);
//                            }

                        }
                        if (PayConfig.ORDER_STATUS_PAYING.equals(response_pay.getPayStatus())) {

                            iScanpayView.showCountDownLoading();
                            iScanpayView.chanageLoadingMsg(response_baseModel.getMsg() + "...");
                            if (response_baseModel.getMsg().contains("等待") && response_baseModel.getMsg().contains("支付密码")) {
                                if (XXPermissions.isHasPermission(context, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(context) != null) {
                                    OrderVoice orderVoice = new OrderVoice();
                                    orderVoice.setContent("请在手机端输入支付密码");
                                    SpeechUtilOffline.getInstance(context).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                                }
                            }
                            orderId = response_pay.getOrderId();
                            intervalStatus();
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                iScanpayView.dismissPayLoading();
                if (e instanceof SocketTimeoutException && PayConfig.TYPE_SUBPAY_TOSCAN.equals(request_pay.getSubPayType())) {
                    iScanpayView.showCountDownLoading();
                    iScanpayView.chanageLoadingMsg("支付中，请稍候...");
                    intervalStatus();
                } else {
                    super.onError(e);
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                iScanpayView.dismissPayLoading();
                IntentHandler.startLoginActivity(context);
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                iScanpayView.dismissPayLoading();
                if (PayConfig.ORDER_STATUS_HUABEI_FAILUER.equals(response_baseModel.getCode())) {
                    // 耗时监控-记录时间 t4_5 : 花呗分期提示使用支付宝  , 无效记录 重置 t0
                    iScanpayView.showHuaBeiDialog();
                } else if (BaseConfigs.NET_ERROR_EOF.equals(response_baseModel.getMsg())) {
                    //返回体解析失败  关单操作
                    iScanpayView.showCountDownLoading();
                    iScanpayView.chanageLoadingMsg(response_baseModel.getMsg());
                    intervalStatus();
                } else {
                    iScanpayView.dismissCountDownLoading();
                    Intent intent = new Intent(context, PayFailureActivity.class);
                    Bundle bundle = new Bundle();
//                        args.setOrderType(dealType);
                    args.setCode(response_baseModel.getCode());
                    args.setPayResultMessage(response_baseModel.getMsg() != null ? response_baseModel.getMsg() : "");
                    bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, args);
                    //  bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            }
        });
    }

    /**
     * 遍历订单状态
     */
    @Override
    public void intervalStatus() {
        unsubscribePeriod();
        periodSubscribtion = observable.subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                getPaymentStatus();
            }
        });
    }

    /**
     * 查询订单状态
     * tips:轮询支付订单结果
     */
    private void getPaymentStatus() {
        final Request_PayStatus request_payStatus = new Request_PayStatus();
        request_payStatus.setClientOrderId(clientOrderId);
//        request_payStatus.setOrderId(orderId); // 不传
//        unsubscribeStatus();
        if (!getStatus) {
            statusSubscribtion = scanpayModel.getPayStatus(request_payStatus, new ApiCallback() {
                @Override
                public void onSuccess(Response_Base response) {
                    if (!isCanceling()) {
                        Response_Pay response_pay = (Response_Pay) response.getResultObject();
                        if (PayConfig.ORDER_STATUS_SUCCESS.equals(response_pay.getPayStatus())) {
                            getStatus = true;
                            iScanpayView.dismissCountDownLoading();
                            //发消息,刷新首页/列表数据
                            RxBus.getInstance().send(Events.EVENT_VOICE_BROADCAT, "scanpay");

                            LogUtils.Log("shibin", "----支付成功#" + response_pay.getOrderId());
                            unsubscribePeriod();
                            unsubscribeStatus();
                            Intent intent = new Intent(context, PaySuccessActivity.class);
                            Bundle resultBundle = new Bundle();
                            args.setReceiptAmount(response_pay.getReceiptAmount());
                            args.setDiscountAmount(response_pay.getDiscountAmount());
                            args.setTotalAmount(response_pay.getTotalAmount());
                            args.setPayType(response_pay.getPayType());
                            args.setOrderId(response_pay.getOrderId());
//                            args.setOrderType(dealType);
//                        args.setGoodsAmount(response_pay.getGoodsAmount());
                            args.setGooodsAmount(response_pay.getGooodsAmount());
                            //营销新增
                            args.setDeductionAmount(response_pay.getDeductionAmount());
                            args.setReceiveAmountFromPayGate(response_pay.getReceiveAmountFromPayGate());

                            resultBundle.putSerializable(PayConfig.INTENT_ORDER_FROM, args);
                            //  resultBundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                            intent.putExtras(resultBundle);
                            context.startActivity(intent);
//                            //打印
//                            if (!PayConfig.TYPE_ORDER_DISH.equals(response_pay.getOrderType())) {
//                                doPrinter(response_pay, null);
//                            }
                        }

                        if (PayConfig.ORDER_STATUS_FAILUER.equals(response_pay.getPayStatus())) {
                            getStatus = true;
                            iScanpayView.dismissCountDownLoading();
                            unsubscribePeriod();
                            unsubscribeStatus();
                            Intent intent = new Intent(context, PayFailureActivity.class);
                            Bundle bundle = new Bundle();
                            args.setCode(response.getCode());
//                            args.setOrderType(dealType);
                            args.setPayResultMessage(response.getMsg() != null ? response.getMsg() : "");
                            bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, args);
                            //  bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean());  // 传递支付监控数据
                            intent.putExtras(bundle);
                            context.startActivity(intent);
                        }
                    }
                }

                @Override
                public void onNeedLogin(String msg) {
                    unsubscribePeriod();
                    unsubscribeStatus();
                    IntentHandler.startLoginActivity(context);
                }

                @Override
                public void onFail(Response_Base response_baseModel) {
                    if (response_baseModel != null && "2017".equals(response_baseModel.getCode())) {
                        getStatus = true;
                        iScanpayView.dismissCountDownLoading();
                        unsubscribePeriod();
                        unsubscribeStatus();
                        Intent intent = new Intent(context, PayFailureActivity.class);
                        Bundle bundle = new Bundle();
                        args.setCode(response_baseModel.getCode());
//                        args.setOrderType(dealType);
                        args.setPayResultMessage(response_baseModel.getMsg() != null ? response_baseModel.getMsg() : "");
                        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, args);
                        // bundle.putSerializable(PayConfig.INTENT_PAY_DATA, getPayDataBean()); // 传递支付监控数据
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }
                }
            });
            subscriptionList.add(statusSubscribtion);
        }
    }


    /**
     * 释放相机资源
     */
    @Override
    public void stopScanner() {
        if (softwareScanner != null) {
            softwareScanner.stopScan();
        }
    }


    @Override
    public void unsubscribePay() {
        if (paySubscribtion != null) {
            paySubscribtion.unsubscribe();
            paySubscribtion = null;
        }
        LogUtils.Log("shibin", " ------ unsubscribePay");

    }

    @Override
    public void unsubscribeStatus() {
        if (subscriptionList != null && subscriptionList.size() > 0) {
            for (Subscription subscription : subscriptionList) {
                if (subscription != null) {
                    subscription.unsubscribe();
                    subscription = null;
                }
            }
            subscriptionList.clear();
        }
        LogUtils.Log("shibin", " ------ unsubscribeStatus");

    }

    @Override
    public void unsubscribePeriod() {
        if (periodSubscribtion != null) {
            periodSubscribtion.unsubscribe();
            periodSubscribtion = null;
        }
        LogUtils.Log("shibin", " ------ unsubscribePeriod");
    }

    @Override
    public String getClientOrderId() {
        return clientOrderId;
    }

    @Override
    public String getOrderId() {
        return orderId;
    }

}